//
//  HMStatusPictureView.swift
//  sinaweibo
//
//  Created by WGP on 16/4/14.
//  Copyright © 2016年 WGP. All rights reserved.
//

import UIKit
import SDWebImage

private let HMStatusPictureCellMargin: CGFloat = 4

private let HMStatusPictureMaxColumn: Int = 3

private let HMStatusPictureViewItemWH =  (UIScreen.mainScreen().bounds.width-CGFloat((HMStatusPictureMaxColumn-1)) * HMStatusPictureCellMargin - 2 * HMStatusCellMargin)/CGFloat(HMStatusPictureMaxColumn)
private let ReuseIdentifier = "item"

class HMStatusPictureView: UICollectionView {
    
    
    private  var layout = UICollectionViewFlowLayout()
    
    var pic_urlsArr: [NSURL]?
    {
        didSet
        {
            let size = calculateSize()
            
            self.snp_updateConstraints { (make) -> Void in
                
                make.size.equalTo(size)
            }
            
//            因为cell的复用重新刷新数据
            reloadData()
        }
    }
    
//    MARK: - 构造方法
    init()
    {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        dataSource = self
        delegate = self
        
        backgroundColor = UIColor.clearColor()
        bounces = false
        showsVerticalScrollIndicator = false
        
//        注册cell
        registerClass(HMStatusPictureViewCell.self, forCellWithReuseIdentifier: ReuseIdentifier)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   
    
   
    private func calculateSize()->CGSize
    {
        layout.itemSize = CGSize(width: HMStatusPictureViewItemWH, height: HMStatusPictureViewItemWH)
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
//        判断图片的数量
        let count = pic_urlsArr?.count ?? 0
        
        if count == 0
        {
            return CGSizeZero
        }
        
        if count == 1
        {
            var size = CGSize(width: HMStatusPictureViewItemWH, height: HMStatusPictureViewItemWH)
            
            let url = pic_urlsArr!.first!
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url.absoluteString)
            {
                size = image.size
                size = CGSize(width: size.width * UIScreen.mainScreen().scale, height: size.height * UIScreen.mainScreen().scale)
            }
            
            if size.width < 40
            {
                size.width = 40
            }
            
            let screenWidth = UIScreen.mainScreen().bounds.width
            
            if size.width > screenWidth * 0.5
            {
                size.width = screenWidth * 0.5
            }
            
            layout.itemSize = size
            return size
        }
        
        layout.minimumLineSpacing = HMStatusPictureCellMargin
        layout.minimumInteritemSpacing = HMStatusPictureCellMargin
        
        var column = HMStatusPictureMaxColumn
        
        if count == 2 || count == 4
        {
            column = 2
        }
        
     // 行数 = (总个数 + 列数 - 1) / 列数
        
        let row = (count + column - 1) / column
        
    // 宽度 = 列数 * item宽度 + (列数 - 1) * 列间距
        
        let width = CGFloat(column) * HMStatusPictureViewItemWH + CGFloat(column-1) * HMStatusPictureCellMargin
     
    // 高度度 = 行数 * item高度 + (行数 - 1) * 行间距
        
        let height = CGFloat(row) * HMStatusPictureViewItemWH + CGFloat(row - 1) * HMStatusPictureCellMargin
        
        return CGSize(width: width, height: height)
        
    }

}


extension HMStatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate
{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pic_urlsArr?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(ReuseIdentifier, forIndexPath: indexPath) as! HMStatusPictureViewCell
        
        cell.imageURL = pic_urlsArr![indexPath.item]
        
        return cell
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let browser = SDPhotoBrowser()
//        原图的父控件
        browser.sourceImagesContainerView = collectionView
//        原图的数量
        browser.imageCount = pic_urlsArr?.count ?? 0
        
//        当前需要展示图片的index
        browser.currentImageIndex = indexPath.item
        
//        代理
        browser.delegate = self
        
        browser.show()
    }
}

extension HMStatusPictureView: SDPhotoBrowserDelegate
{
//    返回临时的占为图(既原来的小图)
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        
//        获取cell
        let cell = cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) as! HMStatusPictureViewCell
        let image = cell.bgImageView.image ?? UIImage(named: "avatar")
        
        return image
    }
    
//    返回高质量的图片的url
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        
        let thumbnailUrl = pic_urlsArr![index].absoluteString
        let newURLStr = thumbnailUrl.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        return NSURL(string: newURLStr)
    }
}

//配图view的自定义cell

class HMStatusPictureViewCell: UICollectionViewCell {
    
//    MARK: - 构造函数
    override init(frame: CGRect) {
      
        super.init(frame: frame)
        
//        准备UI
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//    MARK: - 属性
    var imageURL: NSURL?
    {
        didSet
        {
//            加载图片
            bgImageView.sd_setImageWithURL(imageURL)
        }
    }
  
//    MARK: - 私有方法
    private func setupUI()
    {
        
//        设置图片的填充模型
        bgImageView.contentMode = .ScaleAspectFill
        bgImageView.clipsToBounds = true
        
//        1.添加控件,cell的子控件都应该添加到contentView上
        contentView.addSubview(bgImageView)
        
//        2.添加约束
        bgImageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
    }
    
//    MARK: - 懒加载
    private lazy var bgImageView: UIImageView = UIImageView()
}












